import React from "react";
import { Button, Form, Input, message as antdMessage } from "antd";
import "./style.scss";
import bg from "../../assets/bg.webp";
import { login, LoginState } from "../../service";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { loginSuccessActionCreator } from "../../store/user/userActions";

const App: React.FC = () => {
  const navigate = useNavigate();
  // 获取 dispatch
  const dispatch = useDispatch();

  const onFinish = async (values: LoginState) => {
    // 发送请求， 同时获取结果
    const { code, data, message } = (await login(values)).data;
    if (code === 200) {
      // 1. 进入首页
      navigate("/home");
      // 2. 友好提示
      antdMessage.success(message);
      // 3. 将数据保存到redux
      dispatch(loginSuccessActionCreator(data));
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div>
      <img src={bg} alt="" className="bg" />
      <div className="signin">
        <h2 style={{ textAlign: "center", marginBottom: 20 }}>用户登录</h2>
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "用户名不可以为空" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "密码不可以为空" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button type="primary" htmlType="reset" block>
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default App;
